package cn.test.future.cf;

import lombok.extern.slf4j.Slf4j;

import java.util.Random;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.ExecutionException;
import java.util.function.Function;
import java.util.function.Supplier;

/**
 * 结果转换测试
 */
@Slf4j
public class CompletableFutureTest3 {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        CompletableFutureTest3 test3 = new CompletableFutureTest3();
        test3.thenApply();

        System.out.println("---------------");

        //test3.thenCompose();
    }

    public void thenCompose() {
        CompletableFuture<Integer> future = CompletableFuture.supplyAsync(new Supplier<Integer>() {
            @Override
            public Integer get() {
                int num = new Random().nextInt(30);
                System.out.println("第一阶段：" + num);
                return num;
            }
        }).thenCompose(new Function<Integer, CompletionStage<Integer>>() {
            @Override
            public CompletionStage<Integer> apply(Integer integer) {

                return new CompletableFuture<>().supplyAsync(new Supplier<Integer>() {
                    @Override
                    public Integer get() {
                        int num = integer * 2;
                        System.out.println("第二阶段：" + num);
                        return num;
                    }
                });
            }
        });

        System.out.println("最终结果：" + future.join());
    }

    public void thenApply() {
        CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
            int result = 100;
            log.debug("一阶段：" + result);
            return result;
        }).thenApply(number -> {
            number *= 3;
            log.debug("二阶段：" + number);
            return number;
        });

        log.debug(future.join().toString());
    }
}
